const sqlite3 = require('sqlite3').verbose();


function sqliteInit() {
    const db = new sqlite3.Database('./mydatabase.db');
    db.serialize(() => {
        db.run(`CREATE TABLE IF NOT EXISTS datasource (id INTEGER PRIMARY KEY AUTOINCREMENT, host TEXT NOT NULL, port INTEGER NOT NULL, user TEXT NOT NULL, password TEXT NOT NULL, database TEXT NOT NULL);`);
    });
    db.close();
}

async function getDatabases() {
    const db = new sqlite3.Database('./mydatabase.db');
    return new Promise((resolve, reject) => {
        db.all("SELECT * FROM datasource", (err, rows) => {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
            db.close();
        });
    });
}
async function getDataBaseOne({
                                  databaseId
                              }) {
    const db = new sqlite3.Database('./mydatabase.db');
    return new Promise((resolve, reject) => {
        db.get('SELECT * FROM datasource WHERE id = ?', [databaseId], (err, row) => {
            if (err) {
                console.error(err.message);
                reject(row)
            } else {
                console.log(row);
                resolve(row)
            }
            db.close()
        });
    });
}

function saveDatabase({id, host, port, user, password, database}) {
    const db = new sqlite3.Database('./mydatabase.db');

    if (id) {
        const sql = `UPDATE datasource
            SET host = ?, port = ?, user = ?, password = ?, database = ?
            WHERE id = ?`;
        db.run(sql, [host, port, user, password, database, id])
    } else {
        db.run("INSERT INTO datasource (host, port,user,password,database) VALUES (?, ?,?,?,?)", [
            host, port, user, password, database
        ]);
    }


// 关闭数据库连接
    db.close();
}

module.exports = {
    getDataBaseOne,
    getDatabases,
    sqliteInit,
    saveDatabase
}